package com.handu.luna.boss.controller;

import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.handu.luna.core.domain.support.FileUploadSupport;

@Controller
public class FileUploadController extends BaseController {

	@RequestMapping(value="upload/{imageType}",method=RequestMethod.POST)
	public @ResponseBody() String processUpload(@RequestParam MultipartFile imgFile,@PathVariable String imageType) throws IOException {
		if (!imgFile.isEmpty()) {
            try {
                return "{\"error\" : 0,\"url\" : \""+(FileUploadSupport.upload(imgFile.getInputStream(),
                        System.currentTimeMillis()+"_s"+imgFile.getOriginalFilename().substring(imgFile.getOriginalFilename().lastIndexOf(".")), FileUploadSupport.ImageType.valueOf(imageType)))+"\"}";
            } catch (Exception e) {
                return "You failed to upload " + imgFile.getName() + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + imgFile.getName() + " because the file was empty.";
        }
	}
	
}
